//
//  VoicePlayManager.m
//  DoctorYL
//
//  Created by Lisa on 16/11/2.
//  Copyright © 2016年 yuntai. All rights reserved.
//

#import "VoicePlayManager.h"
#import "TFAudioPlayer.h"
#import "IWxChatMgrChatDefs.h"
#import "NSString+Path.h"

#import <AVFoundation/AVFoundation.h>


@interface VoicePlayManager ()<AVAudioPlayerDelegate>

//音频播放
@property (nonatomic,strong) AVPlayer *avPLayer;//播放在线音频
@property (nonatomic, strong) TFAudioPlayer *audioPlayer;//播放录音


@end

@implementation VoicePlayManager


static VoicePlayManager *sharedInstance = nil;

#pragma mark - Public methods

+ (VoicePlayManager *)shareInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[VoicePlayManager alloc]init];
        [sharedInstance updateAudioSession];
    });
    
    return sharedInstance;
}
/**
 *  播放本地文件
 *
 *  @param filePath
 */
- (BOOL)preparePlayWithFilePath:(NSString *)filePath
{
    [self updateAudioSession];
    [self stopVoicePlay];
    NSData * audioData;
    NSError *error;
    NSString *localFilePathName = [NSString wbChatPathWithType:kChatMsgBody_Voice];
    localFilePathName = [localFilePathName stringByAppendingPathComponent:filePath];
    audioData = [NSData dataWithContentsOfFile:localFilePathName];
    self.audioPlayer = [[TFAudioPlayer alloc] initWithData:audioData error:&error];
    self.audioPlayer.delegate = self;
    if (error) {
        return NO;
    }
    [self.audioPlayer play];
    return YES;
}
/**
 *  播放在线音频
 *
 */
- (BOOL)preparePlayWithConnectUrlStr:(NSString *)connectUrlStr
{
    [self updateAudioSession];
    [self stopVoicePlay];

    NSURL *url = [[NSURL alloc]initWithString:connectUrlStr];
    AVPlayerItem *songItem = [[AVPlayerItem alloc]initWithURL:url];
    [songItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(voicePlayDidEnd:)
                                                 name:AVPlayerItemDidPlayToEndTimeNotification
                                               object:songItem];

    self.avPLayer = [[AVPlayer alloc]initWithPlayerItem:songItem];
    
    self.avPLayer.volume = 0.5f;
    [self.avPLayer play];
    
    return YES;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItem * item = (AVPlayerItem *)object;
        if (item.status == AVPlayerItemStatusReadyToPlay) {
            
        }else if (item.status == AVPlayerItemStatusFailed){
            [HUDManager showWarningWithText:@"播放失败"];
            [self stopVoicePlay];
            if (self.delegate && [self.delegate respondsToSelector:@selector(voiceEndPlayVoicePlayManager:)]) {
                [self.delegate voiceEndPlayVoicePlayManager:self];
            }
        }
    }
}

/**
 *  语音停止播放
 */
- (void)stopVoicePlay
{
    if(self.avPLayer){
        [self.avPLayer pause];
        [[NSNotificationCenter defaultCenter] removeObserver:self
                                                        name:AVPlayerItemDidPlayToEndTimeNotification
                                                      object:self.avPLayer.currentItem];
        self.avPLayer = nil;
    }
    if ([self.audioPlayer isPlaying]) {
        [self.audioPlayer stop];
        self.audioPlayer = nil;
    }
}
- (void)voicePlayDidEnd:(AVPlayerItem *)playItem
{
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:AVPlayerItemDidPlayToEndTimeNotification
                                                  object:playItem];
    
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(voiceEndPlayVoicePlayManager:)]) {
        [self.delegate voiceEndPlayVoicePlayManager:self];
    }
    
}
#pragma mark - AVAudioPlayerDelegate
//播放结束
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player
                       successfully:(BOOL)flag
{
    NSLog(@"-- audioPlayerDidFinishPlaying -- 播放结束 －－");
    if (self.delegate && [self.delegate respondsToSelector:@selector(voiceEndPlayVoicePlayManager:)]) {
        [self.delegate voiceEndPlayVoicePlayManager:self];
    }

}
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player
                                 error:(NSError * __nullable)error
{
    NSLog(@"--audioPlayerDecodeErrorDidOccur--error = %@",error);
}

#pragma mark - Private methods
- (void)updateAudioSession
{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *err = nil;
    [audioSession setCategory :AVAudioSessionCategoryPlayback error:&err];
}

@end
